<template>
  <div>
    <el-dialog
      :title="titlecom"
      :visible.sync="dialogFormVisible"
      width="1200px"
    >
      <el-form
        :model="form"
        label-width="100px"
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" class="specificationInput"></el-input>
        </el-form-item>
        <el-form-item label="封面图" :label-width="formLabelWidth" prop="image">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="comodityUpload"
            :show-file-list="false"
            :limit="1"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="form.image" alt="" />
          </el-dialog>
          <div class="lunboTag">建议尺寸：200*200</div>
        </el-form-item>
        <el-form-item
          label="轮播图"
          :label-width="formLabelWidth"
          prop="content"
        >
          <el-upload
            action=""
            :http-request="uploadFile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            multiple
            :file-list="imgList"
            :limit="10"
            class="avatar-uploader"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible1">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
          <!-- <draggable v-model="imgList" :animation="1000">
            <div v-for="item in imgList" :key="item.id">{{ item.name }}</div>
          </draggable> -->

          <draggable v-model="imgList" :options="{ handle: '.handle' }">
            <div
              v-for="(file, index) in imgList"
              :key="index"
              class="sortable-item"
            >
              <i class="el-icon-menu handle"></i>
              <!-- <img :src="file.url" class="sortable-img" width="10%"> -->
              <el-dialog :visible.sync="dialogVisible1">
                <img
                  width="100%"
                  :src="dialogImageUrl"
                  alt=""
                  class="sortable-img"
                />
              </el-dialog>
            </div>
          </draggable>

          <div class="lunboTag">
            建议尺寸：200*200，可拖拽改变图片顺序，默认首张图为主图，最多上传10张
          </div>
        </el-form-item>

        <!-- <el-form-item
          label="服务分类"
          :label-width="formLabelWidth"
          prop="phone"
        >
          <el-select v-model="form.servetypeid" placeholder="请选择">
            <el-option
              v-for="a in reqCategory1"
              :key="a.id"
              :label="a.name"
              :value="a.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否推荐" :label-width="formLabelWidth" prop="pwd">
          <el-select v-model="form.recommend" placeholder="请选择">
            <el-option
              v-for="a in reqCategory2"
              :key="a.id"
              :label="a.name"
              :value="a.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth" prop="content">
          <editor-bar
            v-model="form.content"
            :isClear="isClear"
            @change="change"
            style="width: 1000px; margin: 0"
          >
          </editor-bar>
        </el-form-item>
      </el-form>
      <!-- <el-form
        :model="item"
        v-for="(item, index) in parameter"
        :key="index"
        label-width="100px"
        class="demo-form"
      >
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="价格" :label-width="formLabelWidth">
              <el-input
                v-model="item.price"
                class="specificationInput1"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="名称">
              <el-input
                v-model="item.name"
                class="specificationInput1"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标题">
              <el-input
                v-model="item.title"
                class="specificationInput1"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button
              type="success"
              @click="addItem()"
              v-if="index == parameter.length - 1"
              >增加</el-button
            >
            <el-button
              type="danger"
              @click="deleteclick(index)"
              v-if="index != 0"
              >删除</el-button
            >
          </el-col>
        </el-row>
      </el-form> -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="quedingtianjia()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addserveadd, updateserveupdate, getservetypes } from "@/api/server";
import { upload } from "@/api/editor.js";
import EditorBar from "@/components/Editor";
import draggable from "vuedraggable";
import { parse } from "path-to-regexp";
export default {
  components: {
    EditorBar,
    draggable,
  },
  data() {
    return {
      parameter: [{ price: "", name: "", title: "" }],
      isClear: false,
      dialogVisible: false,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {
        name: "",
        image: "",
        content: "",
        servetypeid: "",
        image: "",
        recommend: "",
        images: [],
      },
      imgList: [],
      dialogImageUrl: "",
      dialogVisible1: false,
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        image: [{ required: true, message: "请选择头像", trigger: "blur" }],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        pwd: [{ required: true, message: "请选择密码", trigger: "blur" }],
      },
      qubie: 0,
      reqCategory1: [],
      reqCategory2: [
        { id: 1, name: "正常" },
        { id: 2, name: "推荐" },
      ],
    };
  },
  mounted() {
    console.log(this.form.servetypeid);
  },
  methods: {
    deleteclick(index) {
      console.log(index);
      this.parameter.splice(index, 1);
    },
    addItem() {
      if (
        this.parameter[this.parameter.length - 1].price == "" ||
        this.parameter[this.parameter.length - 1].name == "" ||
        this.parameter[this.parameter.length - 1].title == ""
      ) {
        return this.$message.error("请填写好上一级的信息,才能继续添加");
      }
      this.parameter.push({
        price: "",
        name: "",
        title: "",
      });
    },
    change() {},
    // 获取二级服务分类列表
    // async getservetypes1() {
    //   let result = await getservetypes();
    //   console.log(result);
    //   if (result.code == 0) {
    //     this.reqCategory1 = result.data;
    //   }
    // },
    add() {
      this.form = {
        name: "",
        image: "",
        phone: "",
        pwd: "",
      };
      // this.form.servetypeid = val.id;
      // this.getservetypes1();
      this.$nextTick(() => {
        this.form.servetypeid = parseInt(this.$route.query.servetypeid);
      });
      this.qubie = 0;
      this.dialogFormVisible = true;
      this.imgList = [];
    },

    edit(val) {
      this.form = {
        name: "",
        image: "",
        phone: "",
        pwd: "",
      };
      // this.getservetypes1();
      this.qubie = 1;
      this.$nextTick(() => {
        this.form.servetypeid = parseInt(this.$route.query.servetypeid);
      });
      this.form = Object.assign(this.form, val);
      this.dialogFormVisible = true;
      this.imgList = [];
      val.images.split(",").forEach((item) => {
        this.imgList.push({ url: item });
        console.log(this.imgList);
      });
    },
    // 关闭
    handleClose() {
      this.dialogFormVisible = false;
      this.$emit("refresh");
    },

    async quedingtianjia() {
      if (this.qubie == 0) {
        let param = {
          name: this.form.name,
          images: this.form.images,
          content: this.form.content,
          servetypeid: parseInt(this.form.servetypeid),
          image: this.form.image,
          recommend: parseInt(this.form.recommend),
          // parameter: JSON.stringify(this.parameter),
        };
        console.log(param);
        let result = await addserveadd(param);
        if (result.code == 0) {
          this.$message({
            message: `添加服务成功`,
            type: "success",
          });
          this.handleClose();
        }
      } else if (this.qubie == 1) {
        let param = {
          id: parseInt(this.form.id),
          name: this.form.name,
          images: this.form.images,
          content: this.form.content,
          servetypeid: parseInt(this.form.servetypeid),
          image: this.form.image,
          recommend: parseInt(this.form.recommend),
          // parameter: JSON.stringify(this.parameter),
        };
        console.log(param);
        let result = await updateserveupdate(param);
        if (result.code == 0) {
          this.$message({
            message: `修改服务成功`,
            type: "success",
          });
          this.handleClose();
        }
      }
    },
    //轮播图上传
    uploadFile(param) {
      var file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      upload(formData, param).then((res) => {
        if (res.code == 0) {
          // ---------------------------这是商品轮播图 最后要通过 图片逗号拼接
          this.imgList.push({ url: res.data });
        }
      });
      console.log(this.imgList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible1 = true;
      console.log(file);
    },
    //轮播图移除图片
    handleRemove(file, fileList) {
      // fileList是剩下的照片
      this.imgList = fileList;
    },
    //图上传
    async comodityUpload(param) {
      var file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      console.log(param);
      // let result = await upload(formData);
      // console.log(result);
      // if (res.code == 0) {
      //   this.form.image = res.data;
      // }
      upload(formData, param).then((res) => {
        console.log(res);
        if (res.code == 0) {
          this.form.image = res.data;
        }
      });
    },
  },
  watch: {
    imgList: {
      handler(newVal) {
        // console.log("监听", newVal);
        // 这里创建新的数组 用逗号进行隔开 主要是接口要求
        let imagesarr = [];
        const result = newVal.map((item) => `${item.url}`).join(",");
        this.form.images = result;
        // console.log("猪嗨", this.form.images);
      },
      deep: true,
    },
  },
  computed: {
    titlecom() {
      if (this.qubie == 0) {
        return "添加服务";
      } else {
        return "修改服务";
      }
    },
  },
};
</script>

<style scoped lang="scss">
.specificationInput {
  width: 250px;
}
.avatar-uploader-icon[data-v-22a48a68] {
  border: 1px dashed #d9d9d9;
  width: 148px;
  height: 148px;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 148px;
  height: 148px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.specificationInput {
  width: 250px;
}

.addguigeBtn {
  margin-left: 100px;
  margin-bottom: 22px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;
}

.avatar {
  width: 180px;
  height: 180px;
  display: block;
}
v-deep .el-upload--picture-card {
  width: 200px !important;
  height: 200px !important;
}
.specificationInput1 {
  width: 150px;
}
</style>
